import { chars } from './constant'
import {getSignCode, rsaEncryptedData, rsadecryptData} from "@/common/js/rsa.js"
import { aesEncrypt } from '@/common/js/crypto'
import moment from 'moment'

/**
 * toast 提示
 */
export const msg = (title = '', param = {}) => {
	if (!title) return;
	uni.showToast({
		title,
		duration: param.duration || 3000,
		mask: param.mask || false,
		icon: param.icon || 'none'
	});
}

// 显示loading
export const showLoading = (title = '') => {
	if (!title) {
		title = '请稍后'
	}
	uni.showLoading({
		title: title
	});
}

export const hideLoading = () => {
	uni.hideLoading()
}

export const logOut = (message) => {
	console.log('>>>>>>>登录超时');
	window.esale.loginOut(message)
}

// 节流，是否正在运行，防止多次请求
let _throttleRunning = false
/**
 * 节流
 * @param {Function} 执行函数
 * @param {Number} delay 延时ms  
 */
export const throttle = (fn, delay = 500) => {
	// 正在运行，这次结束
	if (_throttleRunning) {
		return;
	}
	//标识正在运行
	_throttleRunning = true;

	// 延时delay毫秒后运行，结束后标识运行结束
	setTimeout(() => {
		fn();
		_throttleRunning = false;
	}, delay);
}

/**
 * 校验格式数据格式
 * @param 要校验的数据
 * @param 什么类型格式
 */
export const checkStr = (str, type) => {
	switch (type) {
		case 'mobile': //手机号码
			return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str);
		case 'tel': //座机
			return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
		case 'card': //身份证
			return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
		case 'mobileCode': //6位数字验证码
			return /^[0-9]{6}$/.test(str)
		case 'pwd': //密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线
			return /^([a-zA-Z0-9_]){6,18}$/.test(str)
		case 'payPwd': //支付密码 6位纯数字
			return /^[0-9]{6}$/.test(str)
		case 'postal': //邮政编码
			return /[1-9]\d{5}(?!\d)/.test(str);
		case 'QQ': //QQ号
			return /^[1-9][0-9]{4,9}$/.test(str);
		case 'email': //邮箱
			return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
		case 'money': //金额(小数点2位)
			return /^\d*(?:\.\d{0,2})?$/.test(str);
		case 'URL': //网址
			return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str)
		case 'IP': //IP
			return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str);
		case 'date': //日期时间
			return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) || /^(\d{4})\-(\d{2})\-(\d{2})$/
				.test(str)
		case 'number': //数字
			return /^[0-9]+$/.test(str);
		case 'english': //英文
			return /^[a-zA-Z]+$/.test(str);
		case 'chinese': //中文
			return /^[\\u4E00-\\u9FA5]+$/.test(str);
		case 'lower': //小写
			return /^[a-z]+$/.test(str);
		case 'upper': //大写
			return /^[A-Z]+$/.test(str);
		case 'HTML': //HTML标记
			return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
		default:
			return true;
	}
}

/**
 * @param {format} 转换后的日期格式，默认yyyy-MM-dd hh:mm:ss
 */
export function format (date, format = "yyyy-MM-dd hh:mm:ss") {
	if (!date) return ''
	//new Date 在 ios safari浏览器有兼容性问题处理如下：
	// ? 兼容safari : 兼容其他浏览器
	let $this = new Date(date) == 'Invalid Date' ? new Date(date.substr(0, 19)) : new Date(date)

	let o = {
		'M+': $this.getMonth() + 1,
		'd+': $this.getDate(),
		'h+': $this.getHours(),
		'm+': $this.getMinutes(),
		's+': $this.getSeconds(),
		'q+': Math.floor(($this.getMonth() + 3) / 3),
		'S': $this.getMilliseconds()
	}
	if (/(y+)/.test(format)) {
		format = format.replace(RegExp.$1, ($this.getFullYear() + '').substr(4 - RegExp.$1.length))
	}
	for (let k in o) {
		if (new RegExp('(' + k + ')').test(format)) {
			format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
		}
	}
	return format
}
/**
* 跳转页面
 * @param {String} url 目标页面地址
 * @param {Object} options 参数
 * @param {Boolean} options.login 是否检测登录  
 */
export function navTo (url, options = {}) {
	if (!url) {
		return;
	}
	if (options.login && !this.$store.getters.hasLogin) {
		url = '/pages/auth/login';
	}
	uni.navigateTo({
		url
	})
}


/**
 * @description 生成随机字符串
 * @param {*} n 整数，需要生产的随机字符串位数
 */
 export function generateMixed(n) {
	let res = "";
	for(let i = 0; i < n ; i ++) {
		let id = Math.ceil(Math.random()*32);
		res += chars[id];
	}
	return res;
}

/**
* @description 生成随机数
* @param {*} n 整数，需要生产的随机数位数
*/
export function rndNum (n) {
   let rnd = ''
   for (let i = 0; i < n; i++)
	   rnd += Math.floor(Math.random() * 35)
   return rnd
}

/**
 * @description 关闭浏览器
 */
export function closeWindow() {
	if(/android/i.test(navigator.userAgent)) {
        document.addEventListener('WeixinJSBridgeReady',function () {WeixinJSBridge.call('closeWindow')},false)
        WeixinJSBridge.call('closeWindow')
    }
    if(/ipad|iphone|mac/i.test(navigator.userAgent)) {
        WeixinJSBridge.call('closeWindow')
    }
}

export function convertCurrency(money) {
	//汉字的数字
	let cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
	//基本单位
	let cnIntRadice = new Array('', '拾', '佰', '仟');
	//对应整数部分扩展单位
	let cnIntUnits = new Array('', '万', '亿', '兆');
	//对应小数部分单位
	let cnDecUnits = new Array('角', '分', '毫', '厘');
	//整数金额时后面跟的字符
	let cnInteger = '整';
	//整型完以后的单位
	let cnIntLast = '元';
	//最大处理的数字
	let maxNum = 999999999999999.9999;
	//金额整数部分
	let integerNum;
	//金额小数部分
	let decimalNum;
	//输出的中文金额字符串
	let chineseStr = '';
	//分离金额后用的数组，预定义
	let parts;
	if (money == '') { return ''; }
	money = parseFloat(money);
	if (money >= maxNum) {
	  //超出最大处理数字
	  return '';
	}
	if (money == 0) {
	  chineseStr = cnNums[0] + cnIntLast + cnInteger;
	  return chineseStr;
	}
	//转换为字符串
	money = money.toString();
	if (money.indexOf('.') == -1) {
	  integerNum = money;
	  decimalNum = '';
	} else {
	  parts = money.split('.');
	  integerNum = parts[0];
	  decimalNum = parts[1].substr(0, 4);
	}
	//获取整型部分转换
	if (parseInt(integerNum, 10) > 0) {
	  let zeroCount = 0;
	  let IntLen = integerNum.length;
	  for (let i = 0; i < IntLen; i++) {
		let n = integerNum.substr(i, 1);
		let p = IntLen - i - 1;
		let q = p / 4;
		let m = p % 4;
		if (n == '0') {
		  zeroCount++;
		} else {
		  if (zeroCount > 0) {
			chineseStr += cnNums[0];
		  }
		  //归零
		  zeroCount = 0;
		  chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
		}
		if (m == 0 && zeroCount < 4) {
		  chineseStr += cnIntUnits[q];
		}
	  }
	  chineseStr += cnIntLast;
	}
	//小数部分
	if (decimalNum != '') {
	  let decLen = decimalNum.length;
	  for (let i = 0; i < decLen; i++) {
		let n = decimalNum.substr(i, 1);
		if (n != '0') {
		  chineseStr += cnNums[Number(n)] + cnDecUnits[i];
		}
	  }
	}
	if (chineseStr == '') {
	  chineseStr += cnNums[0] + cnIntLast + cnInteger;
	} else if (decimalNum == '') {
	  chineseStr += cnInteger;
	}
	return chineseStr;
  }
/**
 * @description 请求头
 * @param {*} isEncryption 是否加密 true 加密 false 不加密
 * @param {*} data 请求数据
 */
export function channelRequestHeadFun (isEncryption,data={}) {
	const random = generateMixed(16)
	const channelCode = 'H5'
	const requestSerialNo = `${channelCode}${moment().format('YYYYMMDDHHmmssSSS')}${rndNum(5)}` // 请求流水号
	const requestTime = moment().format('YYYY-MM-DD HH:mm:ss') // 当前时间
	let headData = {
		deviceId: uni.getStorageSync('systemInfo').deviceId || '16638296896114684503',
		deviceType: uni.getStorageSync('systemInfo').model || '-',
		os: uni.getStorageSync('systemInfo').system || 'Android 12',
		apiVersion: '2.0.0',
		requestIp: sessionStorage.getItem('cip') || '192.168.8.103',
		channelCode,
		requestSerialNo,
		requestTime,
		token: uni.getStorageSync('token') || '',
		sign: 'gdsdkdkdsldsdshdshdksdhssdhsh',
  }
	let aesData  = ''
	console.log('接口原始请求参数：', data);
	if (isEncryption) {
		aesData  = aesEncrypt(JSON.stringify(data),random)
		const sign = `channelCode=${channelCode}requestSerialNo=${requestSerialNo}requestTime=${requestTime}token=${headData.token}${aesData}requestIp=${headData.requestIp}deviceId=${headData.deviceId}`
		headData.sign = `${getSignCode(sign)}`
		headData.random = rsaEncryptedData(random)
	}
	return { headData, aesData }
}

/**
 * 格式化金额  10000 => 10,000
 * @param {*} params 
 */
 export function formartMoney(num) {
	let numStr = num +''
  return numStr.replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,')
	// 保留多少位小数点
	// return (+num || 0).toFixed(2).replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,')
}

// 脱敏银行卡号
export function desensitizationCardNo (str) {
	if (str) {
		if (str.length > 5) {
			let start = str.substring(0,4)
			let end = str.substring(str.length-4, str.length)
			return start + '****' + end
		} else {
			return str
		}
	} else {
		return '-'
	}
}

// 脱敏文本
export function desensitizationText (str) {
	if (str) {
		let text = ''
		if (str.length === 1) {
			text = '*'
		} else if (str.length === 2) {
			text = str.substring(0,1) + '*'
		} else  if (str.length < 6) {
			// {
			text = str.substring(0,1)
			text = text + '****'
			// for (let i = 0; i < str.length-1; i++) {
			// 	if (i != 0 && i != str.length.length-1) {
			// 		text = text + "*"
			// 	}
			// }
			text = text + str.substring(str.length-1,str.length)
		} else {
			text = str.substring(0,2)
			// for (let i = 2; i < str.length - 2; i++) {
			// 	text = text + "*"
			// }
			text = text + "****"
			text = text + str.substring(str.length-2,str.length) 
		}
		return text
	} else {
		return str
	}
}
// 脱敏手机号码 
export function desensitizationPhone (str) {
	if (str) {
		if (str.length > 4) {
			let start = str.substring(0,3)
			let end = str.substring(str.length-4, str.length)
			return start + '****' + end
		} else {
			return str
		}
	} else {
		return '-'
	}
}

// 复制
export function copyText (text) {
	var textAreaCopy = document.createElement('textarea')
	textAreaCopy.setAttribute('readonly', 'readonly')
	textAreaCopy.value = text
	document.body.appendChild(textAreaCopy)
	textAreaCopy.select()
	var res = document.execCommand('copy')
	document.body.removeChild(textAreaCopy)
	return res
}

// 获取时间对应的颜色
export function getTimeAndColor (time) {
	var targetTime = Date.parse(time)
	var time = new Date().getTime()
	var distance = time - targetTime	
	var day = parseInt(distance / (24 * 3600 * 1000))// 天数
	var hour = parseInt(distance / (3600 * 1000)) // 小时数
	var minute = parseInt(distance / (60 * 1000)); // 分钟数
	if ( day > 0 ) {
		return { color: "#FF3B30", time: `${day} 天`}
	} else if ( hour > 0 ) {
		return { color: "#F0C65D", time: `${hour} 小时`}
	} else {
		return { color: "#00A210", time: `${minute} 分钟`}
	}
}

export function getAddress(address){
	if (address) {
		return address.province+"-"+address.city+"-"+address.town
	} else {
		return ''
	}
}

// 还款方式转码
export function changeCodeToStr (dictListData, code) {
	if (!dictListData || dictListData.length == 0 || !code) {
		return code
	}
	let str = code
	dictListData.forEach(element => {
		if (element.dictNo == code) {
			str = element.dictName
		}
	});
	return str
}

// 对象深拷贝
export function deepCopy (src, dest) {
  dest = dest || {}

  for (let item in src) {
    if ((typeof src[item] === 'object') && src[item] !== null) {
      dest[item] = src[item].constructor === Array ? [] : {}
      deepCopy(src[item], dest[item])
    } else {
      dest[item] = src[item]
    }
  }

  return dest
}

export function isvalidPhone(phone) {
  const isPhone = /^1([38][0-9]|4[014-9]|[59][0-35-9]|6[2567]|7[0-8])\d{8}$/ //11位合法手机号码
  const isMob1 = /0\d{2,3}\d{7,8}/ //不带-的座机：02985111752
  const isMob2 = /^([0-9]{3,4}-)?[0-9]{7,8}$/ //带一个-：029-85111752
  const isMob3 = /^\d{3,4}-\d{3,4}-\d{3,4}$/; //带三个-： 0752-250-520
	// 无语，单位电话哪有带*和#
	const isMob4 = /^\d{3,4}#\d{3,4}#\d{3,4}$/; //带三个-： 0752-250-520
  const isMob5 = /^([0-9]{3,4}#)?[0-9]{7,8}$/ //带一个-：029-85111752
	const isMob6 = /^\d{3,4}\*\d{3,4}\*\d{3,4}$/; //带三个-： 0752-250-520
  const isMob7 = /^([0-9]{3,4}\*)?[0-9]{7,8}$/ //带一个-：029-85111752
  if (isMob1.test(phone) || isMob2.test(phone) || isMob3.test(phone) || isPhone.test(phone) 
		|| isMob4.test(phone) || isMob5.test(phone) || isMob6.test(phone) || isMob7.test(phone)
	) {
    return true
  } else {
    return false
  }
}

// 校验单位电话 -- 无语  1-20位，纯数字，英文字符中的' - '' * '' # '
export function validatePhone(phone) {
	let number = /^[0-9#*-]*$/
	return number.test(phone)
}